@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

REM Kafka Tool 服务启动脚本 (Windows版本)
REM 启动后端服务和WebSocket服务

echo ========================================
echo    Kafka Tool 服务启动脚本 v2.0
echo ========================================
echo.

REM 检查Python是否可用
py --version >nul 2>&1
if !errorlevel! neq 0 (
    python --version >nul 2>&1
    if !errorlevel! neq 0 (
        echo 错误: Python 未安装或不在PATH中
        echo 请安装Python 3.8+或将Python添加到PATH
        pause
        exit /b 1
    )
    set PYTHON_CMD=python
) else (
    set PYTHON_CMD=py
)

REM 检查虚拟环境是否存在
if not exist ".venv" (
    echo 虚拟环境不存在，正在创建...
    %PYTHON_CMD% -m venv .venv
    if !errorlevel! neq 0 (
        echo 错误: 创建虚拟环境失败
        pause
        exit /b 1
    )
    echo 虚拟环境创建成功
)

REM 检查虚拟环境中的Python是否存在
if not exist ".venv\Scripts\python.exe" (
    echo 错误: 虚拟环境损坏，请删除.venv文件夹后重新运行
    pause
    exit /b 1
)

echo 使用虚拟环境: .venv\Scripts\python.exe

REM 检查依赖是否已安装
echo 检查依赖...
.venv\Scripts\python.exe -c "import django" >nul 2>&1
if !errorlevel! neq 0 (
    echo Django未安装，正在安装依赖...
    .venv\Scripts\python.exe -m pip install -r requirements.txt
    if !errorlevel! neq 0 (
        echo 错误: 依赖安装失败
        pause
        exit /b 1
    )
    echo 依赖安装完成
)

REM 检查kafka-python兼容性
.venv\Scripts\python.exe -c "from kafka import KafkaProducer" >nul 2>&1
if !errorlevel! neq 0 (
    echo 检测到kafka-python兼容性问题，正在处理...
    .venv\Scripts\python.exe -m pip uninstall kafka-python -y >nul 2>&1
    .venv\Scripts\python.exe -m pip install confluent-kafka >nul 2>&1
    echo Kafka依赖已更新为confluent-kafka
)

REM 检查端口是否被占用
echo 检查端口占用情况...
netstat -an | findstr ":8001" | findstr "LISTENING" >nul
if !errorlevel! equ 0 (
    echo 警告: 端口 8001 已被占用，尝试停止相关服务...
    for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":8001"') do taskkill /PID %%a /F >nul 2>&1
)

netstat -an | findstr ":8002" | findstr "LISTENING" >nul
if !errorlevel! equ 0 (
    echo 警告: 端口 8002 已被占用，尝试停止相关服务...
    for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":8002"') do taskkill /PID %%a /F >nul 2>&1
)

REM 创建日志目录
if not exist "logs" mkdir logs

REM 检查数据库配置
echo 检查数据库配置...
.venv\Scripts\python.exe manage.py check --database default >nul 2>&1
if !errorlevel! neq 0 (
    echo 数据库连接失败，切换到SQLite...
    .venv\Scripts\python.exe -c "import os; content=open('kafkatool/settings.py').read(); content=content.replace(\"'ENGINE': 'django.db.backends.mysql'\", \"'ENGINE': 'django.db.backends.sqlite3'\").replace(\"'NAME': 'kafkatool'\", \"'NAME': 'db.sqlite3'\"); open('kafkatool/settings.py', 'w').write(content)" >nul 2>&1
)

REM 运行数据库迁移
echo 运行数据库迁移...
.venv\Scripts\python.exe manage.py migrate >nul 2>&1
if !errorlevel! neq 0 (
    echo 迁移失败，重新创建迁移...
    if exist "db.sqlite3" del "db.sqlite3" >nul 2>&1
    if exist "api\migrations\*.py" (
        for %%f in (api\migrations\*.py) do (
            if not "%%~nf"=="__init__" del "%%f" >nul 2>&1
        )
    )
    .venv\Scripts\python.exe manage.py makemigrations >nul 2>&1
    .venv\Scripts\python.exe manage.py migrate >nul 2>&1
)

REM 启动WebSocket服务 (Daphne)
echo 启动WebSocket服务 (端口: 8001)...
start /b "WebSocket Service" cmd /c ".venv\Scripts\daphne.exe -b 0.0.0.0 -p 8001 kafkatool.asgi:application > logs\websocket.log 2>&1"
echo WebSocket服务已启动

REM 等待2秒确保WebSocket服务启动
timeout /t 2 /nobreak >nul

REM 启动Django后端服务
echo 启动Django后端服务 (端口: 8002)...
start /b "Backend Service" cmd /c ".venv\Scripts\python.exe manage.py runserver 0.0.0.0:8002 > logs\backend.log 2>&1"
echo Django后端服务已启动

REM 等待3秒让服务完全启动
timeout /t 3 /nobreak >nul

echo.
echo === 验证服务状态 ===

REM 检查WebSocket服务
netstat -an | findstr ":8001" | findstr "LISTENING" >nul
if !errorlevel! equ 0 (
    echo ✓ WebSocket服务: http://127.0.0.1:8001 [运行中]
) else (
    echo ✗ WebSocket服务: 启动失败，请查看 logs\websocket.log
)

REM 检查Django服务
netstat -an | findstr ":8002" | findstr "LISTENING" >nul
if !errorlevel! equ 0 (
    echo ✓ Django后端服务: http://127.0.0.1:8002 [运行中]
) else (
    echo ✗ Django后端服务: 启动失败，请查看 logs\backend.log
)

echo.
echo === 服务信息 ===
echo 前端开发服务器: cd vue-kafka-tool && npm run serve
echo 访问地址: http://localhost:8080
echo.
echo === 日志文件 ===
echo WebSocket日志: logs\websocket.log
echo 后端服务日志: logs\backend.log
echo.
echo === 管理命令 ===
echo 停止服务: stop_services.bat
echo 查看状态: status_services.bat
echo 查看日志: type logs\websocket.log 或 type logs\backend.log
echo.
echo === 故障排除 ===
echo 如果服务启动失败，请检查:
echo 1. Python环境是否正确安装
echo 2. 虚拟环境是否完整
echo 3. 端口是否被其他程序占用
echo 4. 查看日志文件获取详细错误信息
echo.
echo 按任意键退出...
pause >nul